package main.userInterface.ioui;


import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import main.demonutils.io.IslandIOController;


public class IslandIOToolPanel extends JPanel {

    private IslandIOController islandIOController;
	    
	private final JLabel dirIntroLab = new JLabel("The current directory is:");
	private JLabel dirLab = new JLabel();
	private JLabel loadStatusMessage = new JLabel();
	private JLabel editStatusMessage = new JLabel();
	private final JLabel explainLab = new JLabel("This Directory contains the following files:");
	private JList<String> choicesArea;
	private JButton chooseFolderButton = new JButton("Choose Directory");
	
	private File[] dirContent = null;

	private JButton saveButton = new JButton("Save");
	private JButton saveAsButton = new JButton("Save As ...");
	private JButton loadButton = new JButton("Load");
	private JButton deleteButton = new JButton("Delete File");

	    
	public IslandIOToolPanel(IslandIOController islandIOControllerImport){
		this.islandIOController = islandIOControllerImport;
        super.setLayout(new BorderLayout());

        JPanel statusPanel = new JPanel(new GridLayout(0,1,0,0));
        statusPanel.add(loadStatusMessage);
        statusPanel.add(editStatusMessage);
        statusPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createCompoundBorder(
                        BorderFactory.createTitledBorder("Current File Status"),
                        BorderFactory.createEmptyBorder(5,5,5,5)),
                statusPanel.getBorder()));
	        
	    JPanel ioPanel = new JPanel(new BorderLayout());

            JPanel loadLabelPanel = new JPanel(new GridLayout(0,1,0,0));
            loadLabelPanel.add(dirIntroLab);
            loadLabelPanel.add(dirLab);
            loadLabelPanel.add(explainLab);
            loadLabelPanel.setAlignmentX(Component.RIGHT_ALIGNMENT);

        ioPanel.add(loadLabelPanel, BorderLayout.PAGE_START);
	        
            JPanel choicesPanel = new JPanel();
            choicesPanel.setLayout(new BoxLayout(choicesPanel,BoxLayout.PAGE_AXIS));

                choicesArea = new JList<String>();
                choicesArea.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                choicesArea.setLayoutOrientation(JList.VERTICAL);
                choicesArea.setVisibleRowCount(8);

                JScrollPane choicesScroll = new JScrollPane(choicesArea);
                choicesScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
                choicesScroll.setAlignmentX(Component.CENTER_ALIGNMENT);

            choicesPanel.add(choicesScroll);

                chooseFolderButton.setAlignmentX(Component.RIGHT_ALIGNMENT);

            choicesPanel.add(chooseFolderButton);

        ioPanel.add(choicesPanel, BorderLayout.CENTER);

            JPanel buttonPanel = new JPanel(new GridLayout(0,1));
            buttonPanel.add(saveButton);
            buttonPanel.add(saveAsButton);
            buttonPanel.add(loadButton);
            buttonPanel.add(deleteButton);

        ioPanel.add(buttonPanel , BorderLayout.PAGE_END);

        ioPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createCompoundBorder(
                        BorderFactory.createTitledBorder("Load and Save"),
                        BorderFactory.createEmptyBorder(5,5,5,5)),
                ioPanel.getBorder()));


        JPanel combinationPanel = new JPanel();
        combinationPanel.setLayout(new BorderLayout());
        combinationPanel.add(statusPanel , BorderLayout.PAGE_START);
        combinationPanel.add(ioPanel , BorderLayout.CENTER);

        JScrollPane combinationScroll = new JScrollPane(combinationPanel);
        combinationScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        combinationScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

	    this.add(combinationScroll , BorderLayout.CENTER);
	    
	    chooseFolderButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                islandIOController.chooseDirectory();
                setStatus();
            }
        });

        saveButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                islandIOController.prepareNewFileLocation();
                islandIOController.saveIsland();
                setStatus();
            }
        });
        
        saveAsButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                islandIOController.prepareNewFileLocation();
                islandIOController.saveIsland();
                setStatus();
            }
        });
        
        loadButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                if (choicesArea.getSelectedIndex() >= 0
                        && choicesArea.getSelectedIndex() < dirContent.length) {
                    islandIOController.loadIsland(dirContent[choicesArea.getSelectedIndex()]);
                } else {
                    JOptionPane.showMessageDialog(null, "No file has been selected to load.");
                }
                setStatus();
            }
        });
        
        deleteButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                if (choicesArea.getSelectedIndex() >= 0
                        && choicesArea.getSelectedIndex() < dirContent.length) {
                    islandIOController.deleteFile(dirContent[choicesArea.getSelectedIndex()]);
                    setStatus();
                } else {
                    JOptionPane.showMessageDialog(null, "No file has been selected to delete.");
                    setStatus();
                }
            }
        });

        choicesArea.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent listSelectionEvent) {
                if(choicesArea.getSelectedIndex() >= 0
                        && choicesArea.getSelectedIndex() < dirContent.length){
                    loadButton.setEnabled(true);
                    deleteButton.setEnabled(true);
                } else {
                    loadButton.setEnabled(false);
                    deleteButton.setEnabled(false);
                }
            }
        });
	    setStatus();
	}



    /**
     * Updates the list of files to display
     */
    public void updateFileView(){
        dirLab.setText(islandIOController.getCurrentDirPathString());
        dirContent = islandIOController.getDirContent();
        String[] names = new String[dirContent.length];
        for(int i = 0 ; i < names.length ; i++){
            names[i] = dirContent[i].getName(); //populate names
        }
        choicesArea.setListData(names);
    }


    /**
     * Gives a readout of the status of the current file
     */
    private void setStatus(){
        if(islandIOController.hasCurrentDir()){
            saveAsButton.setEnabled(true);

            if(islandIOController.hasCurrentFile()){
                saveButton.setEnabled(true);
                loadStatusMessage.setText(
                        "This island is " + islandIOController.getCurrentFileName() + ".");
                if(islandIOController.isEdited()){
                    editStatusMessage.setText(
                            "\nThe island has not been edited.");
                }else{
                    editStatusMessage.setText(
                            "\nThe island has been edited but not saved.");
                }
            }else{
                saveButton.setEnabled(false);
                loadStatusMessage.setText("This is a new, unsaved island.");
                if(islandIOController.isEdited()){
                    editStatusMessage.setText("\nThe set has not been edited.");
                }else{
                    editStatusMessage.setText("\nThe set has been edited.");
                }

            }

        } else {
            saveButton.setEnabled(false);
            saveAsButton.setEnabled(false);
            loadButton.setEnabled(false);
            deleteButton.setEnabled(false);
        }

        updateFileView();
    }
}